﻿using System;

namespace new_problem
{
    internal class LocalCorrections
    {

                //g - теоретическое поле, x,y - сетка
        public static Double[,] CalcLocalCorrections(double[,] g, double[] x, double[] y, DataBuffer current)
        {
            double eps = 0.01;  
            double alpha = 0.1;   //параметр регуляризации
            Double[,] z0 = DataGen.StartApproximation(); //начальное приближение
            Double[,] u = DataGen.GetFieldGridBySurf(x, y, z0);
            Double[,] zk = new double[DataGen.N + 1, DataGen.N + 1]; // for result

            double nrm = MiscUtils.Norm(g);
            //Double maxErr = 0;
            double err = 1.0;
            int k = 0;
            while (err > eps && k < 20000)
            {
                for (int i = 0; i <= DataGen.N; i++)
                    for (int j = 0; j <= DataGen.N; j++)
                        //zk[i, j] = z0[i, j] / (1 + alpha * z0[i, j] * (g[i, j] - u[i, j]) * Math.Sign(z0[i, j] - DataGen.h));
                        zk[i, j] = z0[i, j] / (1 + alpha * z0[i, j] * (g[i, j] - u[i, j]));

                z0 = zk;
                u = DataGen.GetFieldGridBySurf(x, y, z0);
                err = MiscUtils.Norm(MiscUtils.SubstractMatrix(u, g)) / nrm;
                //alpha = 0.1;
                Console.WriteLine(k + ": " + err + ", alpha: " + alpha);
                k++;
            }
            current.Lc = k;
            current.LcErr = err;
            return MiscUtils.SubstractMatrix(new double[DataGen.N + 1, DataGen.N + 1], zk);
        }
    }
}
